package org.example.config;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.entity.CacheUserInfoVo;
import org.example.constans.BaseCodeEnum;
import org.example.constans.EssenceConstants;
import org.example.utils.HttpUtil;
import org.example.utils.ObjectToHashMapConverter;
import org.example.utils.RedisKeyUtil;
import org.example.utils.SessionUser;
import org.example.utils.redis.ServerRedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Autowired
    private ServerRedisClient serverRedisClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = null;
        try {
            //放行OPTIONS请求
            String method = request.getMethod();
            if ("OPTIONS".equals(method)) {
                return true;
            }
            CacheUserInfoVo userInfo = null;
            // 获取token
            userToken = request.getHeader(EssenceConstants.TOKEN);
            log.info("LoginInterceptor token ={},uri={}，ip={}", userToken, request.getRequestURI(), HttpUtil.getIpAddress());
            if (userToken != null) {
                // 根据token 获取redis中的用户信息
                    Map<String, String> redisCacheUserInfo = serverRedisClient.hgetAll(String.format(RedisKeyUtil.USER_LOGIN_TOKEN_KEY,userToken));
                 if(!CollectionUtils.isEmpty(redisCacheUserInfo)){
                 userInfo = new CacheUserInfoVo();
                 ObjectToHashMapConverter.setValuesToObject(redisCacheUserInfo,userInfo);
                 }


//
//                userInfo = new CacheUserInfoVo();
//                Map<String, String> cacheUserInfo = new HashMap<>();
//                cacheUserInfo.put("account","123");
//                cacheUserInfo.put("email","37314253");
//                ObjectToHashMapConverter.setValuesToObject(cacheUserInfo,userInfo);


            }
            // 获取的用户信息 放到session中
            if (userInfo != null) {
                SessionUser.setSessionUserInfo(userInfo);
                return true;
            }
            responseResult(response, BaseCodeEnum.LOGIN_EXPIRE.getMsg());
            return false;
        } catch (Exception e) {
            log.error("LoginInterceptor error token ={},uri={}", userToken, request.getRequestURI(), e);
            responseResult(response, BaseCodeEnum.SERVER_BUSY.getMsg());
        }
        return true;
    }

    private void responseResult(HttpServletResponse response, String msg) throws Exception {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.getWriter().write(msg);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //一次请求后需要删除线程变量，否则会造成内存泄漏
        SessionUser.remove();
    }
}
